package com.db.ionio.serialization;

import com.google.gson.Gson;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class JsonSerializer implements Serializer<SensorData[]> {
    @Override
    public String getType() {
        return "json";
    }

    private final Gson gson = new Gson();

    @Override
    public void serialize(SensorData[] obj, OutputStream outStream) throws Exception {
        JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(outStream));
        gson.toJson(obj, SensorData[].class, jsonWriter);
        jsonWriter.flush();
    }

    @Override
    public SensorData[] deserialize(InputStream inStream) throws Exception {
        JsonReader reader = new JsonReader(new InputStreamReader(inStream));
        return gson.fromJson(reader, SensorData[].class);
    }
}
